package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 登录控制层
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    /**
     * 快速登录
     * @param map
     * @return
     */
    @PostMapping("/check")
    public Result check(@RequestBody Map map, HttpServletResponse response){
        //取出参数
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");

        //校验验证码
        //判空
        String redisCode = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_LOGIN + telephone);
        if (validateCode == null || telephone == null) {
            return new Result(false, MessageConstant.PARAM_ERROR);
        }
        //比对
        if (!validateCode.equals(redisCode) || StringUtils.isEmpty(redisCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //会员操作
        Member member =memberService.findMemberByTel(telephone);

        //会员不存在空注册会员
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setMaxAge(60*60*2);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
